//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package controller;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import model.User;
import service.UserService;
import service.impl.UserServicelmpl;

@WebServlet(name = "LoginServlet",urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    UserService userService = new UserServicelmpl();

    public LoginServlet() {
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String rememberMe = request.getParameter("rememberMe");
        User userIndb = null;

        try {
            userIndb = this.userService.getUserByName(username);
        } catch (SQLException var9) {
            throw new RuntimeException(var9);
        }

        if (userIndb == null) {
            request.setAttribute("msg", "当前用户名未注册");
            request.getRequestDispatcher("/register.jsp").forward(request, response);
        } else if (userIndb.getPassword().equals(password)) {
            if ("yes".equals(rememberMe)) {
                Cookie usernameCookie = new Cookie("username", username);
                Cookie passwordCookie = new Cookie("password", password);
                usernameCookie.setMaxAge(604800);
                passwordCookie.setMaxAge(604800);
                response.addCookie(usernameCookie);
                response.addCookie(passwordCookie);
            }

            HttpSession session = request.getSession();
            session.setAttribute("username", username);
            response.sendRedirect(request.getContextPath() + "/user");
        } else {
            request.setAttribute("msg", "密码错误");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        }

    }
}

